<?php
/**
 * Code Update Script
 * Update all code references to use new gf_ prefixed table names
 * 
 * Usage: php update_code_references.php
 */

echo "🔧 Updating code references to use gf_ prefixed tables...\n\n";

// Define table mapping for code updates
$tableMappings = [
    // Old table names => New gf_ prefixed names
    'anti_fraud' => 'gf_anti_fraud',
    'api_keys' => 'gf_api_keys',
    'apps' => 'gf_apps',
    'attribution' => 'gf_attribution',
    'et_apps' => 'gf_et_apps',
    'et_apps_apps' => 'gf_et_apps_apps',
    'et_apps_event' => 'gf_et_apps_event',
    'et_apps_web' => 'gf_et_apps_web',
    'et_system_email' => 'gf_et_system_email',
    'et_system_email_config' => 'gf_et_system_email_config',
    'et_users' => 'gf_et_users',
    'fingerprints' => 'gf_fingerprints',
    'merchants' => 'gf_merchants',
    'stats_daily' => 'gf_stats_daily'
];

$baseDir = __DIR__ . '/../../..';
$updatedFiles = [];
$totalReplacements = 0;

// Function to update PHP files
function updatePHPFiles($dir, $mappings, &$updatedFiles, &$totalReplacements) {
    $files = glob($dir . '/**/*.php');
    
    foreach ($files as $file) {
        $content = file_get_contents($file);
        $originalContent = $content;
        $fileReplacements = 0;
        
        // Replace table references in Db::table() calls
        foreach ($mappings as $oldTable => $newTable) {
            // Pattern for Db::table('table_name')
            $pattern = "/Db::table\(['\"]" . preg_quote($oldTable, '/') . "['\"]\)/";
            $replacement = "Db::table('$newTable')";
            
            $newContent = preg_replace($pattern, $replacement, $content);
            if ($newContent !== $content) {
                $replacements = substr_count($content, "Db::table('$oldTable')") + substr_count($content, 'Db::table("' . $oldTable . '")');
                $fileReplacements += $replacements;
                $totalReplacements += $replacements;
                $content = $newContent;
            }
            
            // Pattern for \think\facade\Db::table('table_name')
            $pattern = "/\\\\think\\\\facade\\\\Db::table\(['\"]" . preg_quote($oldTable, '/') . "['\"]\)/";
            $replacement = "\think\facade\Db::table('$newTable')";
            
            $newContent = preg_replace($pattern, $replacement, $content);
            if ($newContent !== $content) {
                $replacements = substr_count($content, "\think\facade\Db::table('$oldTable')") + substr_count($content, '\think\facade\Db::table("' . $oldTable . '")');
                $fileReplacements += $replacements;
                $totalReplacements += $replacements;
                $content = $newContent;
            }
            
            // Pattern for protected $table = 'table_name' in models
            $pattern = "/protected\s+\$table\s*=\s*['\"]" . preg_quote($oldTable, '/') . "['\"]/";
            $replacement = "protected \$table = '$newTable'";
            
            $newContent = preg_replace($pattern, $replacement, $content);
            if ($newContent !== $content) {
                $replacements = substr_count($content, "protected \$table = '$oldTable'") + substr_count($content, 'protected $table = "' . $oldTable . '"');
                $fileReplacements += $replacements;
                $totalReplacements += $replacements;
                $content = $newContent;
            }
        }
        
        if ($content !== $originalContent) {
            file_put_contents($file, $content);
            $updatedFiles[] = [
                'file' => str_replace($baseDir, '', $file),
                'replacements' => $fileReplacements
            ];
            echo "  ✅ Updated: " . str_replace($baseDir, '', $file) . " ($fileReplacements replacements)\n";
        }
    }
}

// Update PHP files
updatePHPFiles($baseDir, $tableMappings, $updatedFiles, $totalReplacements);

echo "\n📊 SUMMARY:\n";
echo "==================================================\n";
echo "Files updated: " . count($updatedFiles) . "\n";
echo "Total replacements: $totalReplacements\n";

if (count($updatedFiles) > 0) {
    echo "\nUpdated files:\n";
    foreach ($updatedFiles as $fileInfo) {
        echo "  - " . $fileInfo['file'] . " (" . $fileInfo['replacements'] . " replacements)\n";
    }
}

echo "\n✅ Code reference update completed!\n";
echo "\n💡 Next steps:\n";
echo "1. Review the updated files to ensure correctness\n";
echo "2. Test your application functionality\n";
echo "3. Run any necessary database migrations\n";

?>